#include "Header.h"
#include "def_pointer.h"

void moveForward(char nextID[4]){
    char tempID[4];
    int32_t tempSize = 0;

    do {
        fread(tempID, 4, 1, fp);
        fread(&tempSize, 4, 1, fp);
        fseek(fp, tempSize, SEEK_CUR);
    } while (nextID[0] != tempID[0] || nextID[1] != tempID[1] || nextID[2] != tempID[2] || nextID[3] != tempID[3]);
    
    fseek(fp, - tempSize -8, SEEK_CUR);
}

void readChunk(struct RiffChunk * rcp){
    fread(rcp, 1, sizeof(* rcp), fp);
}

void printChunk(struct RiffChunk * rcp){
    printf("%s\n", "[chunk]");
    printf("ChunkID=\"%c%c%c%c\"\n", (* rcp).chunkID[0], (* rcp).chunkID[1], (* rcp).chunkID[2], (* rcp).chunkID[3]);
    printf("ChunkSize=%d\n", (* rcp).chunkSize);
    printf("Format=%c%c%c%c\n\n", (* rcp).format[0], (* rcp).format[1], (* rcp).format[2], (* rcp).format[3]);
}

void readSubchunk1(struct FmtChunk * fcp){
    fread(fcp, 1, sizeof(* fcp), fp);
    fseek(fp, (* fcp).chunkSize + 8 - sizeof(* fcp), SEEK_CUR);
}

void printSubchunk1(struct FmtChunk * fcp){
    printf("%s\n", "[fmt]");
    printf("SubChunkID=\"%c%c%c%c\"\n", (* fcp).chunkID[0], (* fcp).chunkID[1], (* fcp).chunkID[2], (* fcp).chunkID[3]);
    printf("SubchunkSize=%d\n", (* fcp).chunkSize);
    printf("AudioFormat=%d\n", (* fcp).audioFormat);
    printf("NumChannels=%d\n", (* fcp).numChannels);
    printf("SampleRate=%d\n", (* fcp).sampleRate);
    printf("ByteRate=%d\n", (* fcp).byteRate);
    printf("BlockAlign=%d\n", (* fcp).blockAlign);
    printf("BitsPerSample=%d\n\n", (* fcp).bitsPerSample);
}

void readSubchunk2(struct DataChunk * dcp){
    fread(dcp, 1, sizeof(* dcp), fp);
}

void printSubchunk2(struct DataChunk * dcp, int channels, int byterate, int bitspersample, int samplerate, double t1, double t2){
    printf("%s\n", "[data]");
    printf("SubchunkID=\"%c%c%c%c\"\n", (* dcp).chunkID[0], (* dcp).chunkID[1], (* dcp).chunkID[2], (* dcp).chunkID[3]);
    printf("SubchunkSize=%d\n", (* dcp).chunkSize);
    printf("DataFrameBegin=%d\n", (int) floor(t1 * byterate));
    printf("DataFrameEnd=%d\n\n", (int) floor(t2 * byterate));
    
    printf("%s\n", "[frames]");
    fseek(fp, (int) floor(t1 * byterate), SEEK_CUR);
    int16_t temp;
    int bytespersample = bitspersample / 8;
    for (int i = 0; i < ((int) floor(t2 * samplerate)) - ((int) floor(t1 * samplerate)); ++i){
        fread(&temp, bytespersample, 1, fp);
        fseek(fp, (channels - 1) * bytespersample, SEEK_CUR);
        printf("%d=%d\n", i, temp);
    }
}

